import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_syt/api/EncryptUtils.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/login/widgets/underline_input_decorator.dart';
import 'package:flutter_syt/domain/widgets/code_form_field.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/event_stream.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/dyt_aliyun_widget.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

@RoutePage(name: "authenticationSecondeForm")
class EpidemicSecondeForm extends StatefulWidget {
  final String? type;

  EpidemicSecondeForm({this.type});

  @override
  _EpidemicSecondeFormState createState() => _EpidemicSecondeFormState();
}

class _EpidemicSecondeFormState extends State<EpidemicSecondeForm> {
  Map labelValue = {
    "birth": S().select_register_birth,
    "license_number": S().select_register_id,
    "cur_city": S().register_city,
    "role": S().register_identity,
  };
  TextEditingController mobileController =
      new TextEditingController(text: UserInfo.me.phone_number);
  String _code = '';

  final _formKey = GlobalKey<FormState>();
  final FocusNode focusNode = FocusNode();
  var formSetting;
  Map formData = new Map();
  bool _checkboxSelected = false;
  bool _isDetail = false;

  @override
  void initState() {
    formSetting = {};
    if (widget.type != '2') {
      _getFormInfo();
    }
    super.initState();
  }

  Future<bool> getSmsCode() async {
    if (mobileController.text == UserInfo.me.phone_number) {
      bool isVertifica = await UtilsOther.checkShowVertification(
          account: mobileController.text,
          context: context,
          status: DytAliyunStatus.DytAliyunStatusMessage);
      if (isVertifica == false) {
        return false;
      }
      bool res = await API.shared.login.getPhoneCode2('authentication');
      return res;
    }
    var code = '86';
    String cachePhoneArea = appContext.storage.getString('login_area') ?? '';
    if (cachePhoneArea != '') {
      code = cachePhoneArea;
    }
    if (_code == '86') {
      if (!RegexUtil.isMobileSimple(mobileController.text)) {
        customShowToast(S.of(context).enter_valid_phone);
        return false;
      }
    } else if (!RegexUtil.matches('^\\d{6,25}\$', mobileController.text)) {
      customShowToast(S.of(context).enter_valid_phone);
      return false;
    }
    bool isVertifica = await UtilsOther.checkShowVertification(
        account: mobileController.text,
        context: context,
        status: DytAliyunStatus.DytAliyunStatusMessage);
    if (isVertifica == false) {
      return false;
    }
    bool res = await API.shared.login
        .getPhoneCode(code, mobileController.text, 'authentication');
    return res;
  }

  Future _getFormInfo() async {
    Map result = await API.shared.user.quetionOptions();
    setState(() {
      formSetting = result;
    });
  }

  Future _report() async {
    if (widget.type != '2') {
      await API.shared.user.authenticationConfirm({
        'type': 2,
        'question': formData.values.toList(),
      });
    }
    if (widget.type == '2') {
      await API.shared.user.authenticationConfirm({
        'type': "1".rsa,
        'phone_number': mobileController.text == UserInfo.me.phone_number
            ? ''
            : mobileController.text.rsa,
        'code': _code.rsa,
        "crypt_type": "rsa",
      });
    }
    await API.shared.user.getUserInfo();
  }

  Future _submit() async {
    final form = _formKey.currentState;
    if (form!.validate()) {
      await loading(_report, text: S.of(context).verifying);
      customShowToast(S.of(context).verify_successful);
      EventStreamController.updateHomeData();
      // return;
      Navigator.of(context)
        ..pop()
        ..pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(
          S.of(context).verify_identity,
        ),
      ),
      body: SafeArea(
        child: GestureDetector(
            onTap: ClickUtils.debounce(() {
              focusNode.unfocus();
            }),
            child: Container(
              child: Column(
                children: [
                  Expanded(
                    child: ListView(
                      children: [
                        Container(
                          width: double.infinity,
                          decoration: BoxDecoration(
                            color: ThemeColor.bkColorFFFFFF,
                          ),
                          child: Form(
                            key: _formKey,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                widget.type == '2'
                                    ? Container(
                                        padding:
                                            EdgeInsets.fromLTRB(20, 0, 20, 0),
                                        margin: EdgeInsets.only(bottom: 20),
                                        child: TextFormField(
                                          inputFormatters: [
                                            FilteringTextInputFormatter.deny(
                                                appContext.emojiRegexp)
                                          ],
                                          enableInteractiveSelection: true,
                                          controller: mobileController,
                                          autofocus: false,
                                          // textAlign: TextAlign.right,
                                          style: TextStyle(
                                            color: ThemeColor.colorBlack100,
                                            fontSize: 16,
                                            height: 1.5,
                                          ),
                                          cursorColor: ThemeColor.primaryColor,
                                          decoration: UnderlineInputDecoration(
                                            hintText: S
                                                .of(context)
                                                .enter_mobile_mumber,
                                          ),
                                          obscureText: false,
                                          validator: (val) {
                                            if (_code == '86') {
                                              if (!RegexUtil.isMobileSimple(
                                                  val!)) {
                                                customShowToast(S
                                                    .of(context)
                                                    .enter_valid_phone);
                                                return '';
                                              }
                                            } else if (!RegexUtil.matches(
                                                '^\\d{6,25}\$', val!)) {
                                              customShowToast(S
                                                  .of(context)
                                                  .enter_valid_phone);
                                              return '';
                                            }
                                            return null;
                                          },
                                          keyboardType: TextInputType.phone,
                                        ),
                                      )
                                    : Container(),
                                widget.type == '2'
                                    ? Padding(
                                        padding:
                                            EdgeInsets.fromLTRB(20, 0, 20, 0),
                                        child: CodeFormField(
                                          tagStr: 'secondeform',
                                          // color: ThemeColor.colorBlack100,
                                          suffixColor: Color(0xFF2942D1),
                                          getSmsCode: getSmsCode,
                                          decoration:
                                              UnderlineInputDecoration(),
                                          onSaved: (val) => _code = val!,
                                        ),
                                      )
                                    : Container(),
                                widget.type != '2'
                                    ? Container(
                                        padding:
                                            EdgeInsets.fromLTRB(15, 0, 15, 15),
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            ...formSetting.keys.map((item) {
                                              return Container(
                                                child: _formItem(
                                                    item, formSetting[item]),
                                              );
                                            }).toList(),
                                          ],
                                        ),
                                      )
                                    : Container(),
                                Container(
                                  padding: EdgeInsets.fromLTRB(15, 16, 15, 15),
                                  child: Text(
                                    S.of(context).auth_hint,
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: ThemeColor.colorBlack100,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ),
                                Container(
                                  padding: EdgeInsets.fromLTRB(0, 0, 15, 15),
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Checkbox(
                                        value: _checkboxSelected,
                                        activeColor: ThemeColor.primaryColor,
                                        checkColor: Colors.black,
                                        onChanged: (value) {
                                          setState(() {
                                            _checkboxSelected =
                                                !_checkboxSelected;
                                          });
                                        },
                                      ),
                                      Expanded(
                                        child: Column(
                                          children: [
                                            SizedBox(
                                              height: 10,
                                            ),
                                            Text(
                                              S.of(context).auth_desc1,
                                              softWrap: true,
                                              style: TextStyle(
                                                fontSize: 12,
                                                color: ThemeColor.colorBlack40,
                                                fontWeight: FontWeight.w400,
                                              ),
                                            ),
                                            SizedBox(
                                              height: 20,
                                            ),
                                            Text(
                                              S.of(context).auth_desc2,
                                              softWrap: true,
                                              style: TextStyle(
                                                fontSize: 12,
                                                color: ThemeColor.colorBlack40,
                                                fontWeight: FontWeight.w400,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  !_isDetail
                      ? Padding(
                          padding: EdgeInsets.fromLTRB(15, 8, 15, 36),
                          child: ElevatedButton(
                              style: (!_checkboxSelected || _isDetail)
                                  ? ElevatedButton.styleFrom(
                                      // onPrimary: Color(0xffdedede),
                                      // primary: Color(0xffdedede),
                                    )
                                  : null,
                              child: Text(
                                S.of(context).submit_auth,
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                  color: ThemeColor.colorBlack100,
                                ),
                              ),
                              onPressed: ClickUtils.debounce(
                                () async {
                                  if (!_checkboxSelected) {
                                    return null;
                                  }
                                  if (_isDetail) {
                                    return null;
                                  }
                                  final form = _formKey.currentState;
                                  if (form!.validate()) {
                                    _submit();
                                  }
                                },
                              )),
                        )
                      : Container(),
                ],
              ),
            )),
      ),
    );
  }

  Widget _formItem(key, options) {
    if (formData[key] == null) {
      formData[key] = {
        "question_key": key,
        "question_value": options[0],
      };
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          labelValue[key],
          style: TextStyle(
            color: ThemeColor.colorBlack100,
            fontWeight: FontWeight.w500,
            fontSize: 16,
          ),
        ),
        ...options.map<Widget>((item) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Radio(
                activeColor: ThemeColor.primaryColor,
                visualDensity: VisualDensity(horizontal: -4),
                value: '$item',
                onChanged: (value) {
                  formData[key] = {
                    "question_key": key,
                    "question_value": value,
                  };
                  setState(() {});
                },
                // 按钮组的值
                groupValue: formData[key]['question_value'],
              ),
              Text(
                '$item',
                style: TextStyle(
                  color: ThemeColor.colorBlack60,
                  fontWeight: FontWeight.w400,
                  fontSize: 16,
                ),
              ),
            ],
          );
        }).toList(),
        Divider(
          color: ThemeColor.dividerColor,
        ),
      ],
    );
  }
}
